<template>
  <div>
    <config-title :com-name="com.name"
                  :com-alias="com.alias"
                  :com-version="com.version"></config-title>
    <div class="com-content-wp">
      <n-data-table
          ref="table"
          size="small"
          :columns="configColumns"
          :data="configData"
          class="m_lr_10"
      />
      <n-divider/>
      <n-alert title="" type="info" class="m_lr_10 com-content-alert">
        <template #header>
          <n-checkbox v-model:checked="com.dataSource.source.useAutoUpdate">启用自动更新</n-checkbox>
        </template>
        <template #icon>
          <i class="iconfont icon-shizhong_f"></i>
        </template>
        频率:
        <n-input-number size="small"
                        :show-button="false"
                        :min="0"
                        v-model:value="com.dataSource.source.autoUpdate"
                        class="com-content-wp_frequency"
                        placeholder=""/>
        秒一次
      </n-alert>
      <n-grid x-gap="12" :cols="4">
        <n-gi>
          <div class="wp_item_title">数据源类型</div>
        </n-gi>
        <n-gi :span="3">
          <n-select size="small" v-model:value="com.dataSource.source.type"
                    :options="dataSourceList" @update:value="handleTypeChange"></n-select>
        </n-gi>
      </n-grid>
      <template v-if="com.dataSource.source.type === 'static'">
        <my-monaco-editor language="json"
                          :code="com.dataSource.source.staticData"
                          :auto-format="true"></my-monaco-editor>
      </template>
      <template v-else>
        <n-grid x-gap="12" :cols="4">
          <n-gi>
            <div class="wp_item_title" v-if="com.dataSource.source.type === 'API'">API接口</div>
            <div class="wp_item_title" v-else-if="com.dataSource.source.type === 'SQL'">SQL接口</div>
            <div class="wp_item_title" v-else-if="com.dataSource.source.type === 'CSV'">CSV接口</div>
          </n-gi>
          <n-gi :span="2">
            <n-select size="small"
                      :options="requestList"
                      :on-update="handleRequestIdChange"
                      v-model:value="com.dataSource.source.requestId"></n-select>
          </n-gi>
          <n-gi>
            <n-button type="primary" size="small" class="base-primary-btn" @click="addSource">新建</n-button>
          </n-gi>
        </n-grid>
        <n-grid x-gap="12" :cols="1">
          <n-gi class="popover_result_btn">
            <n-spin :show="requestSpin">
              <span v-if="com.dataSource.source.requestId" @click="handleRequestData">查看数据源响应结果</span>
            </n-spin>
          </n-gi>
        </n-grid>
      </template>
    </div>
    <n-drawer
        v-model:show="responseDrawer"
        :width="400"
        placement="right"
    >
      <n-drawer-content title="数据响应结果" class="responseDrawerContent">
        <n-grid x-gap="12" :cols="4">
          <n-gi :span="4">
            <n-checkbox v-model:checked="com.dataSource.source.config.useFilter">数据过滤器
              <n-tag type="primary" style="cursor: pointer;">已添加1个过滤器</n-tag>
            </n-checkbox>
          </n-gi>
        </n-grid>
        <n-grid x-gap="12" :cols="4">
          <n-gi>
            <div class="wp_item_title">选择过滤器</div>
          </n-gi>
          <n-gi :span="2">
            <n-select size="small" v-model:value="com.dataSource.source.type"
                      :options="dataSourceList" @update:value="handleTypeChange"></n-select>
          </n-gi>
          <n-gi>
            <n-button size="small" type="primary" class="base-primary-btn">新建过滤器</n-button>
          </n-gi>
        </n-grid>
        <n-grid x-gap="12" :cols="1">
          <n-gi>
            <data-filter></data-filter>
          </n-gi>
        </n-grid>
        <n-grid x-gap="12" :cols="1">
          <n-gi class="popover_result_content">
            数据响应结果
          </n-gi>
        </n-grid>
        <n-grid x-gap="12" :cols="1">
          <n-gi class="popover_result_content">
            <my-monaco-editor language="json"
                              :height="460"
                              :code="com.dataSource.source.requestData"
                              :auto-format="true"></my-monaco-editor>
          </n-gi>
        </n-grid>
      </n-drawer-content>
    </n-drawer>
  </div>
</template>

<script>
import { computed, defineComponent, h, inject, onMounted, provide, ref } from "vue";
import ConfigTitle from "../components/config-title.vue";
import { getApiData, getDataAPIAllList, } from "../../../../service/data_api";
import { getCSVData, getDataCSVAllList, } from "../../../../service/data_csv";
import { getDataSQLAllList, getSQLData } from "../../../../service/data_sql";
import { setMyData } from "./../../../../mixins/data-center.js";
//
// import {
//   NAlert,
//   NButton,
//   NCheckbox,
//   NCollapse,
//   NCollapseItem,
//   NDataTable,
//   NDivider,
//   NDrawer,
//   NDrawerContent,
//   NForm,
//   NFormItem,
//   NGi,
//   NGrid,
//   NInput,
//   NInputNumber,
//   NRadio,
//   NSelect,
//   NSpin,
//   NTag
// } from "naive-ui";
import { dataSourceList } from "../../../../utils/dict";
import { useRouter } from "vue-router";
import DataFilter from "./data-filter/index.vue";
import { useStore } from "vuex";

export default defineComponent({
  name: "data-center-panel",
  components: {
    ConfigTitle,
    // NForm, NFormItem, NGi, NGrid, NInput, NInputNumber, NDataTable,
    // NCollapse, NRadio, NButton,
    // NCollapseItem, NSelect, NDivider, NAlert, NCheckbox,
    // NDrawer,
    // NDrawerContent, NTag, DataFilter, NSpin
  },
  setup(props) {
    const router = useRouter();
    const store = useStore();
    const requestSpin = ref(false);
    const pageFilters = computed(() => store.state.design.pageFilters);
    const com = inject("com");
    const responseDrawer = ref(false);
    const configColumns = [
      {
        title: "字段",
        key: "filed",
        width: "70px"
      },
      {
        title: "映射",
        key: "reflect",
        render(row) {
          return h(
              NSelect,
              {
                size: "small",
                options: reflectList.value,
                placeholder: "",
              },
          );
        }
      },
      {
        title: "说明",
        key: "explain",
        align: "center",
        width: "70px"
      },
      {
        title: "状态",
        key: "status",
        align: "center",
        width: "70px"
      },
    ];
    const configData = [{
      key: 0,
      filed: "content",
      reflect: "",
      explain: "内容",
      status: "x",
    }, {
      key: 1,
      filed: "url",
      reflect: "",
      explain: "超链接",
      status: "x",
    },];
    const reflectList = ref([{
      label: "content",
      value: "content"
    }, {
      label: "url",
      value: "url"
    }]);
    const apiList = ref([]);
    const sqlList = ref([]);
    const csvList = ref([]);
    const requestList = computed(() => {
      let list = [];
      switch (com.value.dataSource.source.type) {
        case "API":
          list = apiList.value;
          break;
        case "SQL":
          list = sqlList.value;
          break;
        case "CSV":
          list = csvList.value;
          break;
        default:
          list = [];
          break;
      }
      return list;
    });
    const staticData = ref([]);
    const getAPIAllList = () => {
      getDataAPIAllList().then(res => {
        apiList.value = res.data.result;
      });
    };
    const getSQLAllList = () => {
      getDataSQLAllList().then(res => {
        sqlList.value = res.data.result;
      });
    };
    const getCSVAllList = () => {
      getDataCSVAllList().then(res => {
        csvList.value = res.data.result;
      });
    };
    const handleRequestData = () => {
      requestSpin.value = true;
      if (responseDrawer.value) {
        responseDrawer.value = !responseDrawer.value;
      } else {
        switch (com.value.dataSource.source.type) {
          case "API":
            getApiData({ data_api_id: com.value.dataSource.source.requestId }).then(res => {
              com.value.dataSource.source.requestData = res.data;
              responseDrawer.value = true;
              requestSpin.value = false;
            });
            break;
          case "CSV":
            getCSVData({ data_csv_id: com.value.dataSource.source.requestId }).then(res => {
              com.value.dataSource.source.requestData = res.data;
              responseDrawer.value = true;
              requestSpin.value = false;
            });
            break;
          case "SQL":
            getSQLData({ data_sql_id: com.value.dataSource.source.requestId }).then(res => {
              com.value.dataSource.source.requestData = res.data;
              responseDrawer.value = true;
              requestSpin.value = false;
            });
            break;
          default:
            requestSpin.value = false;
            break;
        }
      }
    };
    const handleTypeChange = () => {
      com.value.dataSource.source.requestId = undefined;
      com.value.dataSource.source.requestData = [];
    };
    const handleRequestIdChange = () => {
      com.value.dataSource.source.requestData = [];
    };
    const addSource = () => {
      let routeData = null;
      switch (com.value.dataSource.source.type) {
        case "API":
          routeData = router.resolve({
            name: "MySourceDataAPI",
          });
          window.open(routeData.href, "_blank");
          break;
        case "SQL":
          routeData = router.resolve({
            name: "MySourceDataSQL",
          });
          window.open(routeData.href, "_blank");
          break;
        case "CSV":
          routeData = router.resolve({
            name: "MySourceDataCSV",
          });
          window.open(routeData.href, "_blank");
          break;
        default:
          break;
      }
    };
    const refreshData = () => {
      setMyData(com.id);
    };
    provide("pageFilters", pageFilters);
    provide("refreshData", refreshData);
    onMounted(() => {
      getAPIAllList();
      getSQLAllList();
      getCSVAllList();
    });
    return {
      com,
      responseDrawer,
      staticData,
      configColumns,
      configData,
      dataSourceList: dataSourceList,
      apiList,
      requestList,
      requestSpin,
      handleRequestData,
      handleTypeChange,
      getAPIAllList,
      getSQLAllList,
      getCSVAllList,
      handleRequestIdChange,
      addSource,
      refreshData
    };
  }
});
</script>

<style lang="less" scoped>
@import "../../../../style/page/design-config.less";

.add_filter {
  display: inline-block;
}

.show_result {
  text-align: center;
  margin-top: 20px;
}

.com-content-alert {
  :deep(.n-alert__icon) {
    margin: auto;
    left: 10px;
    bottom: 0;

    & > i {
      font-size: 24px;
    }
  }
}

.com-content-wp_frequency {
  width: 80px;
  display: inline-block;

  :deep(.n-input) {
    height: 20px;

    input {
      height: 20px;
    }
  }
}

.popover_result_btn {
  display: inline-block;
  cursor: pointer;
  color: #2681ff;
  transition: color .2s;
  border: 1px solid #4f9eff;
  width: 180px;
  margin: 22px auto 0;
  text-align: center;

  &:hover {
    color: #409fff;
  }
}

.popover_result_content {
  width: 100%;
}

.responseDrawerContent {
  :deep(.n-drawer-body-content-wrapper) {
    padding: 8px;

    .n-grid {
      padding: 4px 4px 4px 8px;
    }
  }
}
</style>